#!/usr/bin/perl
use lib "$ENV{MYSQL_DRAW}/lib";
use PairedReadFlagStat;
use DepthCoverage;
use VariantEval;
use strict;
use Data::Dumper;
use Getopt::Long;
use DBI;

my ($readgroup_name, $sample_name, $insert);
my @argv = @ARGV;
&GetOptions("insert!"=> \$insert,
            "readgroup_name=s" => \$readgroup_name,
            "sample_name=s" => \$sample_name);

if ((!$readgroup_name) || (!$sample_name)) {
	die "usage: $0 --sample_name PSP7000 --readgroup_name Project_47885PSP7000 --insert\n(use --insert only when data are ready to be inserted into mysql table)\n";
}

my $stat_path = "stat";
my $vcf_path = "vcf";
die "could not find stat or vcf directory\n" unless ((-d $stat_path) && (-d $vcf_path));
my $lane = "s_$sample_name";

if ($insert) {
	print STDERR "$readgroup_name to be inserted into ReadGroup.\n";
}
else {
	print Dumper(@argv);
}

my $dbh = DBI->connect($ENV{dbi1}, $ENV{dbi2}, $ENV{dbi3});

my $readgroup_table_id = MyTools::fetchrow1col1_arrayref($dbh, "select RGID from ReadGroup where ", {'ReadGroupName' => "$readgroup_name"});
printf STDERR "$readgroup_name: $readgroup_table_id\n";

## filename prefix mapps to modifier, which distinguishes various leves of filtering or scopes
my $PRflagstat = {'prefix' => {"$lane" => "initial", "${lane}_nodup" => "nodup", "${lane}_nodup_uniq" => "nodup_uniq"}, 
									'field_list' => ["total","duplicates"]};
#									'field_list' => ["total","duplicates","mapped", "properly paired"]};

my $depthcvg = {'prefix' => {"${lane}_genome" => 'genome',
															"${lane}_target" => 'target',
															"${lane}_nodup_genome" => 'nodup_genome',
															"${lane}_nodup_target" => 'nodup_target',
															"${lane}_nodup_uniq_recal_genome" => 'nodup_uniq_genome',
															"${lane}_nodup_uniq_recal_target" => 'nodup_uniq_target',
															"${lane}_nodup_uniq_recal_flank" => 'nodup_uniq_flank'},
								'field_list' => ["sample_id", "total","mean"]};

my $cumulat_cvg_counts = {'prefix' => {"${lane}_genome" => 'genome',
															"${lane}_target" => 'target',
															"${lane}_nodup_genome" => 'nodup_genome',
															"${lane}_nodup_target" => 'nodup_target',
															"${lane}_nodup_uniq_recal_genome" => 'nodup_uniq_genome',
															"${lane}_nodup_uniq_recal_target" => 'nodup_uniq_target',
															"${lane}_nodup_uniq_recal_flank" => 'nodup_uniq_flank'},
											'field_list' => ["gte_0","gte_1",'gte_0-gte_1']};

my $cumulat_cvg_proportions = {'prefix' => {
															"${lane}_nodup_uniq_recal_genome" => 'nodup_uniq_genome',
															"${lane}_nodup_uniq_recal_target" => 'nodup_uniq_target',
															"${lane}_nodup_uniq_recal_flank" => 'nodup_uniq_flank'},
											'field_list' => ["gte_2","gte_10","gte_20","gte_30","gte_40","gte_50"]};

my $variant_eval = {'prefix' => {
															"${lane}_nodup_uniq_recal.FULL_mbq_20_mmq_30_filtered_nomask" => 'target'},
#															"${lane}_merged_nodup_uniq_recal_mbq_20_mmq_30_filtered" => 'target'},
#															"${lane}_nodup_uniq_recal_mbq_20_mmq_30_filtered" => 'target'},
#															"${lane}_nodup_uniq_recal_mbq_20_mmq_30_filtered_flank" => 'flank'},
											'field_list' => { 'CompOverlap' => ['nEvalVariants','novelSites','nVariantsAtComp','compRate','concordantRate'],
																				'TiTvVariantEvaluator' => ['tiTvRatio']}};
#CompOverlap  CompRod  EvalRod  JexlExpression  Novelty  nEvalVariants  nCompVariants  novelSites  nVariantsAtComp  compRate           nConcordant  concordantRate   

my @RV_arr = ();

## flagstat
my $prev_RV;
foreach my $prefix (sort keys %{$PRflagstat->{'prefix'}}) {
	printf STDERR "$stat_path/$prefix\t$PRflagstat->{'prefix'}->{$prefix}\n";
	my $RV = readPairedReadFlagStat($dbh, "$stat_path/$prefix", "$PRflagstat->{'prefix'}->{$prefix}", $PRflagstat->{'field_list'});
	if ($PRflagstat->{'prefix'}->{$prefix} eq 'initial') {
		$prev_RV = $RV;
	}
	elsif ($PRflagstat->{'prefix'}->{$prefix} eq 'nodup') {
		$prev_RV->{2}->{'value'} = $prev_RV->{1}->{'value'} - $RV->{5}->{'value'};
		$prev_RV->{4}->{'value'} = $prev_RV->{2}->{'value'}/$prev_RV->{1}->{'value'};	
		$prev_RV = $RV;
	}
	elsif ($PRflagstat->{'prefix'}->{$prefix} eq 'nodup_uniq') {
		$prev_RV->{7}->{'value'} = $prev_RV->{5}->{'value'} - $RV->{9}->{'value'};
		$prev_RV->{8}->{'value'} = $prev_RV->{7}->{'value'}/$prev_RV->{5}->{'value'};	
	}
	push @RV_arr, $RV;
}

## depthCoverage
foreach my $prefix (keys %{$depthcvg->{'prefix'}}) {
#	printf STDERR "$stat_path/$prefix\t$depthcvg->{'prefix'}->{$prefix}\n";
	my ($RV, $VR) = readDepthCoverage($dbh, "$stat_path/$prefix", "sample_summary", "$depthcvg->{'prefix'}->{$prefix}", $depthcvg->{'field_list'});
	push @RV_arr, $RV;
}

## cumulative coverage counts
foreach my $prefix (keys %{$cumulat_cvg_counts->{'prefix'}}) {
#	printf STDERR "$stat_path/$prefix\t$cumulat_cvg_counts->{'prefix'}->{$prefix}\n";
	my ($RV, $VR) = readDepthCoverage($dbh, "$stat_path/$prefix", "sample_cumulative_coverage_counts", "$cumulat_cvg_counts->{'prefix'}->{$prefix}", $cumulat_cvg_counts->{'field_list'});
	my $perc_not_covered = ($RV->{$VR->{'gte_0'}}->{'value'} - $RV->{$VR->{'gte_1'}}->{'value'}) / $RV->{$VR->{'gte_0'}}->{'value'} * 100;
	$RV->{$VR->{'gte_0-gte_1'}}->{'value'} = $perc_not_covered;
	push @RV_arr, $RV;
}

## cumulative coverage proportions
foreach my $prefix (keys %{$cumulat_cvg_proportions->{'prefix'}}) {
#	printf STDERR "$stat_path/$prefix\t$cumulat_cvg_proportions->{'prefix'}->{$prefix}\n";
	my ($RV, $VR) = readDepthCoverage($dbh, "$stat_path/$prefix", "sample_cumulative_coverage_proportions", "$cumulat_cvg_proportions->{'prefix'}->{$prefix}", $cumulat_cvg_proportions->{'field_list'});
	map{$RV->{$_}->{'value'} *= 100} keys %{$RV}; # convert decimal fraction to %
	push @RV_arr, $RV;
}

## variant_eval
foreach my $prefix (keys %{$variant_eval->{'prefix'}}) {
#	printf STDERR "$stat_path/$prefix\t$variant_eval->{'prefix'}->{$prefix}\n";
	my $RV = readVariantEval($dbh, "$vcf_path/$prefix", "eval", "$variant_eval->{'prefix'}->{$prefix}", $variant_eval->{'field_list'});
	push @RV_arr, $RV;
}

my $sth = $dbh->prepare("INSERT INTO Metric VALUES (?,?,?,?,)") if ($insert == 1);

open(FOUT, ">${sample_name}_speek.txt") or die "Couldn't open ${sample_name}_speek.txt\n";
foreach my $rv (@RV_arr) {
	printf STDERR "%s\n", join("\n", map{"$sample_name\t$readgroup_table_id\t$_\t$rv->{$_}->{'field_name'}\t$rv->{$_}->{'value'}"} sort keys %{$rv});	
	if ($insert == 1) {
		foreach my $k (sort keys %{$rv}) {
			next if ($k =~ /13|16|19|22|25|28|31/); #sample_name; should be removed from table metric_info eventually
			$sth->execute(0,$readgroup_table_id, $k, $rv->{$k}->{'value'});
		}
	}
	else {
		foreach my $k (sort keys %{$rv}) {
			next if ($k =~ /13|16|19|22|25|28|31/); #sample_name; should be removed from table metric_info eventually
			printf FOUT "0\t$readgroup_table_id\t$k\t$rv->{$k}->{'value'}\n";	
		}
	}
}
close FOUT;

